package com.zimug.boot.launch.service;


import com.zimug.boot.launch.mapper.ArticleMapper;
import com.zimug.boot.launch.model.Article;
import com.zimug.boot.launch.model.ArticleVO;
import com.zimug.boot.launch.utils.DozerUtils;
import org.dozer.Mapper;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ArtivleServiceImpl implements  ArticleService {


  @Resource
  protected Mapper dozerMapper;

  @Resource
  private ArticleMapper articleMapper;

  public static final String CACHE_OBJECT = "article";  //缓存名称
  public static final String CACHE_LIST_KEY  = "\"list\"";


  //新增
  @Override
  @CacheEvict(value = CACHE_OBJECT,key = CACHE_LIST_KEY)   //删除List集合缓存
  public void saveArticle(ArticleVO article) {
    Article articlePO = dozerMapper.map(article, Article.class);
    articleMapper.insert(articlePO);
  }

  //删除
  @Override
  @Caching(evict = {
          @CacheEvict(value = CACHE_OBJECT,key = CACHE_LIST_KEY),   //删除List集合缓存
          @CacheEvict(value = CACHE_OBJECT,key = "#id")  //删除单条记录缓存
  })
  public void deleteArticle(Long id) {
    articleMapper.deleteById(id);
  }


  @Caching(evict = {
          @CacheEvict(value = CACHE_OBJECT,key = CACHE_LIST_KEY)   //删除List集合缓存
  },put={
          @CachePut(value = CACHE_OBJECT,key = "#article.getId()") ,  //删除单条记录缓存
  })
  public ArticleVO updateArticle2(ArticleVO article) {
    Article articlePO = dozerMapper.map(article,Article.class);
    articleMapper.updateById(articlePO);

    return article; //TODO CachePut缓存值要与数据库一致，所以要去数据库查询
  }

  //更新
  @Override
  @Caching(evict = {
          @CacheEvict(value = CACHE_OBJECT,key = CACHE_LIST_KEY),   //删除List集合缓存
          @CacheEvict(value = CACHE_OBJECT,key = "#article.getId()")  //删除单条记录缓存
  })
  public void updateArticle(ArticleVO article) {
    Article articlePO = dozerMapper.map(article,Article.class);
    articleMapper.updateById(articlePO);
  }

  //查询
  @Override
  @Cacheable(value = CACHE_OBJECT,key="#id",sync=true )
  public ArticleVO getArticle(Long id) {

    return dozerMapper.map(articleMapper.selectById(id),ArticleVO.class);
  }

  //查询所有
  @Override
  @Cacheable(value = CACHE_OBJECT,key=CACHE_LIST_KEY )
  public List<ArticleVO> getAll() {
    List<Article> articles = articleMapper.selectList(null);
    return DozerUtils.mapList(articles,ArticleVO.class);
  }
}
